# Copyright Authors of Cilium
# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)

include ../../Makefile.defs

MAKEFLAGS += -r

CLANG ?= clang

FLAGS := -I$(ROOT_DIR)/bpf -I$(ROOT_DIR)/bpf/include -g

# Base CFLAGS (CLANG_FLAGS) are read from pkg/datapath/loader/compile.go
# to keep them synced with the loader
CLANG_FLAGS := $(FLAGS) $(shell $(GO) run $(ROOT_DIR)/pkg/datapath/loader/tools/clang_cflags.go)

# Create dependency files for each .o file.
CLANG_FLAGS += -MD

# Mimics the mcpu values set by cilium-agent. See GetBPFCPU().
CLANG_FLAGS += -mcpu=v3

# Autogenerated scapy pkts
SCAPY_HDR := $(ROOT_DIR)/bpf/tests/output/gen_pkts.h
SCAPY_HDR_TS := $(ROOT_DIR)/bpf/tests/output/gen_pkts.h.stamp
TRACE_PIPE_LOG := $(ROOT_DIR)/bpf/tests/output/trace_pipe.log
TRACE_PIPE_PID := $(ROOT_DIR)/bpf/tests/output/trace_pipe.pid

.PHONY: all clean run $(SCAPY_HDR_TS)

ALL_TEST_OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))

ifeq ($(origin BPF_TEST), undefined)
TEST_OBJECTS = $(ALL_TEST_OBJECTS)
else
TEST_OBJECTS=$(shell echo $(ALL_TEST_OBJECTS) | tr ' ' '\n' | grep $(BPF_TEST).o)
ifeq ($(strip $(TEST_OBJECTS)),)
$(error Invalid test '$(BPF_TEST).o')
endif
endif

all: $(TEST_OBJECTS)

$(SCAPY_HDR_TS):
	$(QUIET) $(ROOT_DIR)/bpf/tests/scapy/./parser.py . > $(SCAPY_HDR).tmp
	$(QUIET) if ! cmp -s $(SCAPY_HDR) $(SCAPY_HDR).tmp; then	\
		mv $(SCAPY_HDR).tmp $(SCAPY_HDR);			\
	else								\
		rm $(SCAPY_HDR).tmp;					\
	fi
	@touch $(SCAPY_HDR_TS)

$(SCAPY_HDR): $(SCAPY_HDR_TS)

%.o: %.c $(LIB) $(SCAPY_HDR)
	@$(ECHO_CC)
	@# Remove the .o file to force recompilation, only rely on make's caching, not clangs
	@rm -f $@
	$(QUIET) ${CLANG} ${CLANG_FLAGS} -c $< -o $@

%.ll: %.c $(LIB)
	@$(ECHO_CC)
	$(QUIET) ${CLANG} ${CLANG_FLAGS} -c -emit-llvm $< -o $@

%.i: %.c $(LIB)
	@$(ECHO_CC)
	$(QUIET) ${CLANG} ${CLANG_FLAGS} -E -c $< -o $@


clean:
	rm -f output/*
	rm -f $(wildcard *.ll)
	rm -f $(wildcard *.o)
	rm -f $(wildcard *.i)
	rm -f $(wildcard *.d)

BPF_TEST_FLAGS:= $(GO_TEST_FLAGS)
SUDO :=
ifneq ($(shell id -u), 0)
		SUDO += sudo -E
		BPF_TEST_FLAGS += -exec "sudo -E"
endif
ifeq ($(V),1)
    BPF_TEST_FLAGS += -test.v
endif
ifeq ($(COVER),1)
	ifndef COVERFORMAT
		COVERFORMAT:=html
	endif
    BPF_TEST_FLAGS += -coverage-report $(ROOT_DIR)/bpf-coverage.$(COVERFORMAT) -coverage-format $(COVERFORMAT)
ifdef NOCOVER
    BPF_TEST_FLAGS += -no-test-coverage "$(NOCOVER)"
endif
endif
ifeq ($(INSTRLOG),1)
    BPF_TEST_FLAGS += -instrumentation-log $(ROOT_DIR)/test/bpf-instrumentation.log
endif
ifdef RUN
    BPF_TEST_FLAGS += -run $(RUN)
endif
ifdef BPF_TEST_DUMP_CTX
    BPF_TEST_FLAGS += -dump-ctx
endif
ifdef BPF_TEST
	BPF_TEST_FLAGS += -test $(BPF_TEST)
endif

run: $(TEST_OBJECTS)
	$(GO) test ./bpftest \
		-bpf-test-path $(ROOT_DIR)/bpf/tests \
		$(BPF_TEST_FLAGS) \
	| $(GOTEST_FORMATTER);

-include $(TEST_OBJECTS:.o=.d)
